import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Input,
  Button,
  Space,
  Typography,
  Select,
  Tag,
  Avatar,
  List,
  Pagination,
  AutoComplete,
  Collapse,
  Form,
  DatePicker,
  Row,
  Col,
  Divider,
  Empty,
  Spin,
  Alert,
  Tooltip,
  Badge,
  Dropdown,
  Menu,
} from 'antd';
import {
  SearchOutlined,
  FilterOutlined,
  BarChartOutlined,
  TeamOutlined,
  HistoryOutlined,
  StarOutlined,
  SettingOutlined,
  ClearOutlined,
  ClockCircleOutlined,
  UserOutlined,
  FileTextOutlined,
  DatabaseOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { searchApi } from '../services/api';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { Panel } = Collapse;

interface SearchResult {
  type: 'telemetry_point' | 'team' | 'extraction_run';
  id: string;
  title: string;
  description?: string;
  highlights?: Record<string, string[]>;
  score: number;
  metadata: Record<string, any>;
}

interface SearchHistory {
  searchId: string;
  query: string;
  type: string;
  resultCount: number;
  searchTime: number;
  createdAt: string;
}

const Search: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [totalResults, setTotalResults] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [searchType, setSearchType] = useState('all');
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [searchHistory, setSearchHistory] = useState<SearchHistory[]>([]);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [facets, setFacets] = useState<Record<string, Record<string, number>>>({});
  const [searchTime, setSearchTime] = useState(0);

  const [advancedForm] = Form.useForm();
  const searchInputRef = useRef<any>(null);

  // 搜索历史本地存储
  const [localHistory, setLocalHistory] = useState<string[]>([]);

  useEffect(() => {
    // 从本地存储加载搜索历史
    const history = localStorage.getItem('searchHistory');
    if (history) {
      setLocalHistory(JSON.parse(history));
    }

    // 加载搜索历史
    loadSearchHistory();
  }, []);

  useEffect(() => {
    // 当用户输入变化时获取建议
    if (searchQuery.length > 0) {
      const debounceTimer = setTimeout(() => {
        getSearchSuggestions(searchQuery);
      }, 300);

      return () => clearTimeout(debounceTimer);
    }
  }, [searchQuery]);

  // 执行搜索
  const handleSearch = async (query?: string, isAdvanced = false) => {
    const searchQueryToUse = query || searchQuery;
    if (!searchQueryToUse.trim()) return;

    setLoading(true);
    setCurrentPage(1);

    try {
      let response;

      if (isAdvanced) {
        const advancedValues = advancedForm.getFieldsValue();
        response = await searchApi.search({
          query: searchQueryToUse,
          filters: {
            team_filter: advancedValues.teamIds?.[0],
            component_filter: advancedValues.telemetryType,
          },
          include_ukm: true,
          include_uma: true,
          include_enums: true,
        }, {
          page: 1,
          page_size: pageSize,
        });
      } else {
        response = await searchApi.search({
          query: searchQueryToUse,
          include_ukm: true,
          include_uma: true,
          include_enums: true,
        }, {
          page: 1,
          page_size: pageSize,
        });
      }

      if (response.data) {
        // Transform API response to match SearchResult interface
        const transformedResults: SearchResult[] = response.data.data.map((item: any) => ({
          type: 'telemetry_point',
          id: item.id.toString(),
          title: item.name,
          description: item.description,
          score: item.match_score || 0,
          highlights: {
            name: [item.name],
            component: item.component ? [item.component] : [],
            file_path: [item.file_path]
          },
          metadata: {
            type: item.type,
            units: item.units,
            component: item.component,
            file_path: item.file_path,
            line_number: item.line_number,
            owner: item.owner,
            assigned_team_id: item.assigned_team_id,
            assigned_team_name: item.assigned_team_name,
            match_fields: item.match_fields
          }
        }));

        setSearchResults(transformedResults);
        setTotalResults(response.data.total || 0);
        setSearchTime(0); // Mock search time
        setFacets({}); // Mock facets
      }

      // 更新本地搜索历史
      if (searchQueryToUse && !localHistory.includes(searchQueryToUse)) {
        const newHistory = [searchQueryToUse, ...localHistory.slice(0, 9)];
        setLocalHistory(newHistory);
        localStorage.setItem('searchHistory', JSON.stringify(newHistory));
      }
    } catch (error: any) {
      console.error('Search failed:', error);
      // 静默处理错误，避免影响用户体验
    } finally {
      setLoading(false);
    }
  };

  // 适配Antd Input.Search的onSearch接口
  const handleSearchInput = (value: string) => {
    handleSearch(value);
  };

  // 处理页面变化
  const handlePageChange = async (page: number, pageSize?: number) => {
    setLoading(true);
    setCurrentPage(page);
    if (pageSize) setPageSize(pageSize);

    try {
      const response = await searchApi.search({
        query: searchQuery,
        include_ukm: true,
        include_uma: true,
        include_enums: true,
      }, {
        page,
        page_size: pageSize || 20,
      });

      if (response.data) {
        // Transform API response to match SearchResult interface
        const transformedResults: SearchResult[] = response.data.data.map((item: any) => ({
          type: 'telemetry_point',
          id: item.id.toString(),
          title: item.name,
          description: item.description,
          score: item.match_score || 0,
          highlights: {
            name: [item.name],
            component: item.component ? [item.component] : [],
            file_path: [item.file_path]
          },
          metadata: {
            type: item.type,
            units: item.units,
            component: item.component,
            file_path: item.file_path,
            line_number: item.line_number,
            owner: item.owner,
            assigned_team_id: item.assigned_team_id,
            assigned_team_name: item.assigned_team_name,
            match_fields: item.match_fields
          }
        }));

        setSearchResults(transformedResults);
        setTotalResults(response.data.total || 0);
      }
    } catch (error) {
      console.error('Search pagination failed:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取搜索建议
  const getSearchSuggestions = async (query: string) => {
    try {
      const response = await searchApi.getSuggestions({
        q: query,
        limit: 10,
      });
      setSuggestions(response.data?.suggestions || []);
    } catch (error) {
      console.error('Failed to get suggestions:', error);
    }
  };

  // 加载搜索历史
  const loadSearchHistory = async () => {
    try {
      // TODO: Implement search history API endpoint
      // const response = await searchApi.getSearchHistory({ limit: 10 });
      setSearchHistory([]);
    } catch (error) {
      console.error('Failed to load search history:', error);
    }
  };

  // 获取类型标签
  const getTypeTag = (type: string) => {
    const typeConfig = {
      telemetry_point: { color: 'blue', text: '遥测点', icon: <BarChartOutlined /> },
      team: { color: 'green', text: '团队', icon: <TeamOutlined /> },
      extraction_run: { color: 'orange', text: '提取任务', icon: <DatabaseOutlined /> },
    };

    const config = typeConfig[type as keyof typeof typeConfig];
    return config ? (
      <Tag color={config.color} icon={config.icon}>
        {config.text}
      </Tag>
    ) : null;
  };

  // 获取结果图标
  const getResultIcon = (type: string) => {
    const iconConfig = {
      telemetry_point: <BarChartOutlined />,
      team: <TeamOutlined />,
      extraction_run: <DatabaseOutlined />,
    };

    return iconConfig[type as keyof typeof iconConfig] || <FileTextOutlined />;
  };

  // 处理结果点击
  const handleResultClick = (result: SearchResult) => {
    switch (result.type) {
      case 'telemetry_point':
        navigate(`/analysis/points/${result.id}`);
        break;
      case 'team':
        navigate(`/teams/${result.id}`);
        break;
      case 'extraction_run':
        navigate(`/extraction/progress/${result.id}`);
        break;
    }
  };

  // 处理搜索历史点击
  const handleHistoryClick = (query: string) => {
    setSearchQuery(query);
    handleSearch(query);
  };

  // 处理高级搜索
  const handleAdvancedSearch = () => {
    handleSearch(undefined, true);
    setShowAdvanced(false);
  };

  // 清除搜索
  const handleClearSearch = () => {
    setSearchQuery('');
    setSearchResults([]);
    setTotalResults(0);
    setFacets({});
    setSearchTime(0);
    searchInputRef.current?.focus();
  };

  // 渲染搜索结果
  const renderSearchResults = () => {
    if (loading) {
      return (
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
          <div style={{ marginTop: '16px' }}>
            <Text>搜索中...</Text>
          </div>
        </div>
      );
    }

    if (searchResults.length === 0 && !searchQuery) {
      return (
        <Card>
          <Empty
            description={
              <div>
                <Paragraph>在上方输入关键词开始搜索</Paragraph>
                <Text type="secondary">
                  您可以搜索遥测点、团队或提取任务
                </Text>
              </div>
            }
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        </Card>
      );
    }

    if (searchResults.length === 0 && searchQuery) {
      return (
        <Card>
          <Empty
            description={`未找到与 "${searchQuery}" 相关的结果`}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          >
            <Space>
              <Button type="primary" onClick={() => setShowAdvanced(true)}>
                尝试高级搜索
              </Button>
              <Button onClick={handleClearSearch}>
                清除搜索
              </Button>
            </Space>
          </Empty>
        </Card>
      );
    }

    return (
      <Card
        title={
          <Space>
            <Text>搜索结果</Text>
            <Text type="secondary">
              找到 {totalResults} 个结果，用时 {searchTime}ms
            </Text>
          </Space>
        }
        extra={
          <Space>
            <Select
              style={{ width: 120 }}
              value={searchType}
              onChange={setSearchType}
            >
              <Option value="all">全部</Option>
              <Option value="telemetry_points">遥测点</Option>
              <Option value="teams">团队</Option>
              <Option value="extractions">提取任务</Option>
            </Select>
            <Button
              icon={<SettingOutlined />}
              onClick={() => setShowAdvanced(!showAdvanced)}
            >
              {showAdvanced ? '简化搜索' : '高级搜索'}
            </Button>
          </Space>
        }
      >
        <List
          dataSource={searchResults}
          renderItem={(item, index) => (
            <List.Item
              key={`${item.type}-${item.id}-${index}`}
              style={{ padding: '16px 0' }}
              onClick={() => handleResultClick(item)}
              actions={[
                <Button
                  type="link"
                  icon={<MoreOutlined />}
                  onClick={(e) => {
                    e.stopPropagation();
                    // 显示更多操作菜单
                  }}
                />
              ]}
            >
              <List.Item.Meta
                avatar={
                  <Avatar
                    icon={getResultIcon(item.type)}
                    style={{
                      backgroundColor: item.type === 'telemetry_point' ? '#1890ff' :
                                     item.type === 'team' ? '#52c41a' : '#faad14'
                    }}
                  />
                }
                title={
                  <Space>
                    <span
                      dangerouslySetInnerHTML={{
                        __html: item.highlights?.name?.[0] || item.title
                      }}
                    />
                    {getTypeTag(item.type)}
                  </Space>
                }
                description={
                  <div>
                    <Paragraph
                      ellipsis={{ rows: 2 }}
                      dangerouslySetInnerHTML={{
                        __html: item.highlights?.description?.[0] || item.description || ''
                      }}
                      style={{ marginBottom: 8 }}
                    />
                    <Space size="large" style={{ fontSize: '12px', color: '#666' }}>
                      {item.type === 'telemetry_point' && item.metadata.teamName && (
                        <Space>
                          <TeamOutlined />
                          <span>{item.metadata.teamName}</span>
                        </Space>
                      )}
                      <Space>
                        <ClockCircleOutlined />
                        <span>{new Date(item.metadata.createdAt).toLocaleDateString()}</span>
                      </Space>
                      {item.score > 0 && (
                        <Space>
                          <StarOutlined />
                          <span>相关度: {item.score}</span>
                        </Space>
                      )}
                    </Space>
                  </div>
                }
              />
            </List.Item>
          )}
        />

        {totalResults > pageSize && (
          <div style={{ textAlign: 'center', marginTop: '24px' }}>
            <Pagination
              current={currentPage}
              total={totalResults}
              pageSize={pageSize}
              showSizeChanger
              showQuickJumper
              showTotal={(total, range) =>
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
              onChange={handlePageChange}
            />
          </div>
        )}
      </Card>
    );
  };

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>
      {/* 搜索头部 */}
      <Row justify="center" style={{ marginBottom: '32px' }}>
        <Col span={16}>
          <Title level={2} style={{ textAlign: 'center', marginBottom: '16px' }}>
            智能搜索
          </Title>
          <AutoComplete
            style={{ width: '100%' }}
            value={searchQuery}
            onChange={setSearchQuery}
            options={suggestions.map(suggestion => ({ value: suggestion, key: suggestion }))}
            onSelect={(value) => {
              setSearchQuery(value);
              handleSearch(value);
            }}
            ref={searchInputRef}
          >
            <Input.Search
              size="large"
              placeholder="搜索遥测点、团队或提取任务..."
              enterButton
              onSearch={handleSearchInput}
            />
          </AutoComplete>
        </Col>
      </Row>

      <Row gutter={16}>
        {/* 左侧栏 */}
        <Col span={6}>
          {/* 快速筛选 */}
          <Card title="快速筛选" style={{ marginBottom: '16px' }} size="small">
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text strong>搜索类型</Text>
                <Select
                  style={{ width: '100%', marginTop: '8px' }}
                  value={searchType}
                  onChange={setSearchType}
                >
                  <Option value="all">全部类型</Option>
                  <Option value="telemetry_points">遥测点</Option>
                  <Option value="teams">团队</Option>
                  <Option value="extractions">提取任务</Option>
                </Select>
              </div>

              {facets.type && (
                <div>
                  <Text strong>结果分类</Text>
                  <div style={{ marginTop: '8px' }}>
                    {Object.entries(facets.type).map(([type, count]) => (
                      <div key={type} style={{ marginBottom: '4px' }}>
                        <Button
                          type={type === searchType ? 'primary' : 'default'}
                          size="small"
                          onClick={() => setSearchType(type)}
                        >
                          {getTypeTag(type)}
                          <Badge count={count} />
                        </Button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </Space>
          </Card>

          {/* 搜索历史 */}
          <Card title="搜索历史" extra={
            localHistory.length > 0 && (
              <Button
                type="text"
                size="small"
                icon={<ClearOutlined />}
                onClick={() => {
                  setLocalHistory([]);
                  localStorage.removeItem('searchHistory');
                }}
              >
                清除
              </Button>
            )
          }>
            {localHistory.length > 0 ? (
              <Space direction="vertical" style={{ width: '100%' }}>
                {localHistory.map((query, index) => (
                  <Button
                    key={index}
                    type="text"
                    icon={<HistoryOutlined />}
                    onClick={() => handleHistoryClick(query)}
                    style={{ textAlign: 'left', width: '100%' }}
                  >
                    {query}
                  </Button>
                ))}
              </Space>
            ) : (
              <Empty
                description="暂无搜索历史"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            )}
          </Card>
        </Col>

        {/* 主要内容区 */}
        <Col span={18}>
          {/* 高级搜索面板 */}
          {showAdvanced && (
            <Card style={{ marginBottom: '16px' }} title="高级搜索">
              <Form
                form={advancedForm}
                layout="vertical"
                onFinish={handleAdvancedSearch}
              >
                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item label="遥测类型" name="telemetryType">
                      <Select placeholder="选择遥测类型" allowClear>
                        <Option value="UMA">UMA</Option>
                        <Option value="UKM">UKM</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="分析状态" name="analysisStatus">
                      <Select placeholder="选择分析状态" allowClear>
                        <Option value="NOT_ANALYZED">待分析</Option>
                        <Option value="ANALYZED">已分析</Option>
                        <Option value="NOT_NEEDED">不需要</Option>
                        <Option value="NEEDS_COLLECTION">需要收集</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="所有者邮箱" name="ownerEmail">
                      <Input placeholder="输入邮箱地址" />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item label="源文件模式" name="sourceFilePattern">
                      <Input placeholder="如: *.xml, histogram*" />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="时间范围" name="dateRange">
                      <RangePicker style={{ width: '100%' }} />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="团队" name="teamIds">
                      <Select mode="multiple" placeholder="选择团队" allowClear>
                        {/* 这里应该加载用户的团队列表 */}
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>

                <Row justify="end">
                  <Space>
                    <Button onClick={() => setShowAdvanced(false)}>
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit">
                      应用筛选
                    </Button>
                  </Space>
                </Row>
              </Form>
            </Card>
          )}

          {/* 搜索结果 */}
          {renderSearchResults()}
        </Col>
      </Row>
    </div>
  );
};

export default Search;